Conditional Statements Exercises

For these exercises, use what you have learned about if,else if, and else statements to answer the questions! The first exercise is done for you as an example:

Example: Write a script that prints "Hello" if the variable x is equal to 1:

In [1]:
x <- 1

if (x ==1){
    print("Hello")
}
[1] "Hello"

Exercise Problems

Ex 1: Write a script that will print "Even Number" if the variable x is an even number, otherwise print "Not Even":

In [ ]:
x <- 3 # Change x to test

Ex 2: Write a script that will print 'Is a Matrix' if the variable x is a matrix, otherwise print "Not a Matrix". Hint: You may want to check out help(is.matrix)

In [6]:
x <- matrix()
[1] "Is a Matrix"

Ex 3: Create a script that given a numeric vector x with a length 3, will print out the elements in order from high to low. You must use if,else if, and else statements for your logic. (This code will be relatively long)

In [10]:
x <- c(3,7,1)
[1] "7 3 1"

Ex 4: Write a script that uses if,else if, and else statements to print the max element in a numeric vector with 3 elements.

In [12]:
x <- c(20, 10, 1)
[1] 20

Great Job!